package com.cjc.sport.serviceimpl;

import com.cjc.sport.entity.Category;
import com.cjc.sport.entity.Course;
import com.cjc.sport.entity.Sort;
import com.cjc.sport.exception.CourseException;
import com.cjc.sport.mapper.CategoryMapper;
import com.cjc.sport.mapper.CourseMapper;
import com.cjc.sport.service.CourseService;
import com.cjc.sport.util.SportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程管理服务层实现类
 *
 * @Author: Bruse Queen
 * @Date: 2018/2/28
 */
@Service(value = "courseService")
public class CourseServiceImpl implements CourseService {

    /**
     * 装配课程mapper
     */
    @Autowired
    private CourseMapper courseMapper;
    /**
     * 引入配置文件
     */
    @Autowired
    private Environment environment;
    /**
     * 装配课程分类id
     */
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增课程
     *
     * @param course 课程对象
     */
    @Override
    public void addCourse(Course course) {
        // 课程类型名
        String tempCategoryName = course.getCategoryName();
        // 根据课程类型和序号查询课程记录
        Course tempCourse = courseMapper.selectCourse(tempCategoryName, course.getCourseNum());

        // 查询课程分类是否存在
        List<Category> categories = categoryMapper.selectCategoryName(tempCategoryName);
        if (categories.size() == 0) {
            throw new CourseException("该课程分类不存在!");
        }

        // 获取课程分类id
        String categpryId = categories.get(0).getCategoryId();
        course.setCategoryId(categpryId);
        if (null != tempCourse) {
            throw new CourseException("已有此序号！");
        }

        // 设置uuid
        course.setCourseId(SportUtils.getUuid());
        // 去除img链接
//        System.out.println(environment.getProperty("img.url"));
//        course.setPicUrl(course.getPicUrl().replace(environment.getProperty("img.url"), ""));
        // 新增成功result为1，失败为0
        int result = courseMapper.insertSelective(course);
        if (1 != result) {
            // 如果新增失败
            throw new CourseException("新增失败！");
        }
        return;
    }

    // 更新课程
    @Override
    public void updateCourse(Course course) {
        // 课程类型名
        String tempCategoryName = course.getCategoryName();
        // 根据课程类型和课程序号查询课程记录
        Course tempCourse = courseMapper.selectCourse(tempCategoryName, course.getCourseNum());

        // 查询课程分类是否存在
        List<Category> categories = categoryMapper.selectCategoryName(tempCategoryName);
        if (categories.size() == 0) {
            throw new CourseException("该课程分类不存在!");
        }

        // 获取课程分类id
        String categpryId = categories.get(0).getCategoryId();
        // 去除img链接
//        System.out.println(environment.getProperty("img.url"));
//        course.setPicUrl(course.getPicUrl().replace(environment.getProperty("img.url"), ""));
        course.setCategoryId(categpryId);
        if (null != tempCourse && !tempCourse.getCourseId().equals(course.getCourseId())) {
            // 如果数据库中相应的课程类型与课程序号已存在，并且数据库中课程记录的id与要修改的课程的id不同
            throw new CourseException("已有此序号！");
        }

        // 查询是否编辑内容
        Course courseTempById = courseMapper.selectByPrimaryKey(course.getCourseId());
        if (course.equals(courseTempById)) {
//            throw new CourseException("您未修改任何信息!");
        }

        // 新增成功result为1，失败为0
        int result = courseMapper.updateByPrimaryKeySelective(course);
        if (1 != result) {
            throw new CourseException("编辑失败！");
        }
        return;
    }

    // 删除课程
    @Override
    public void deleteCourseById(String courseId) {
        // 新增成功result为1，失败为0
        int reslut = courseMapper.deleteByPrimaryKey(courseId);
        if (1 != reslut) {
            throw new CourseException("删除失败！");
        }
        return;
    }


    // 批量地给课程排序
    @Override
    public void sortCourse(List<Sort> sorts, int pageNum, int pageSize,
                           String courseName, String categoryName, String courseTag) {
        // 解析排序集合
        List<Course> courseList = new ArrayList<Course>();
        for (Sort sort : sorts) {
            Course course = new Course();
            course.setCourseId(sort.getKey());
            course.setCourseNum(sort.getValue());
            courseList.add(course);
        }
        // 特别说明，如果以后需要开启分页排序，将分页打开，然后前端传入正确带分页数据即可
        // 设置分页
//        PageHelper.startPage(pageNum, pageSize);
        // 获取旧数据
        List<Course> coursesOld = courseMapper.selectActionSql(courseName, categoryName, courseTag);
        if (coursesOld.size() != courseList.size()) {
            throw new CourseException("数据异常，请刷新后再试！");
        }
        // 新旧数据交替赋值
        for (int i = 0; i < courseList.size(); i++) {
            courseList.get(i).setCourseNum(coursesOld.get(i).getCourseNum());
        }

        // 执行排序
        for (Course course : courseList) {
            int reslut = courseMapper.updateByPrimaryKeySelective(course);
            if (1 != reslut) {
                throw new CourseException("排序过程中出错！");
            }
        }
        // 对序号进行重新排序
        List<Course> coursesAll = courseMapper.selectActionSql(courseName, categoryName, courseTag);
        for (int i = 0; i != coursesAll.size(); i++) {
            Course courseTemp = coursesAll.get(i);
            courseTemp.setCourseNum(i + 1);
            int j = courseMapper.updateByPrimaryKeySelective(courseTemp);
            if (j != 1) {
                throw new CourseException("对序号进行重新排序时出错！");
            }
        }

        return;
    }

    @Override
    public List<Course> selectByCondition(String courseName, String categoryName,
                                          String courseTag) {
        // 执行查询
        List<Course> courses = courseMapper.selectActionSql(courseName, categoryName, courseTag);

        // 查询是否有数据
        if (courses.isEmpty()) {
            throw new CourseException("暂无相关数据！");
        }

//         设置imgUrl
        for (Course course : courses) {
            course.setPicUrl(environment.getProperty("img.url") + course.getPicUrl());
        }
//        System.out.println(environment.getProperty("img.url"));
//        courses.forEach(c -> c.setPicUrl(environment.getProperty("img.url") + c.getPicUrl()));
        return courses;
    }
}
